using Mono.Cecil.Cil;

namespace Cil.Ast;

public sealed class ReturnExpression : SingleInstructionExpression
{
    public const int ReturnPos = 0;
    public const int MaxNodes = 1;

    public ReturnExpression(Context context, Instruction inst, Expression? result = null)
        : base(context, inst)
    {
        // base class
        ReadsStack = result != null ? 1 : 0;
        WritesStack = 0;
        Nodes = new FixedList<Expression>(MaxNodes);

        // this class
        Result = result ?? new Expression(context);
    }

    public Expression Result
    {
        get => Nodes[ReturnPos];
        private set
        {
            Nodes[ReturnPos] = value;
            value.ParentNode = this;
        }
    }

    public override string ToString()
    {
        return $"return{(ReadsStack > 0 ? " " + Result : "")}{FinalString}";
    }
}

public static partial class IlAst
{
    public static ReturnExpression Return(Context context, Instruction position, Expression result = null)
    {
        return new ReturnExpression(context, position, result);
    }
}